var media_manager = liwe.module ( "media_manager" );

media_manager.init = function ()
{
	media_manager.em = new liwe.event_manager ( media_manager );
	media_manager.valid_events ( [ 'gallery', 'close' ] );
};

/*redefine WWW_arrowBoxtemplates*/
WWL.arrowbox.templates = {
        "nav-next" : '<div id="move_next_%(name)s" class="wwl_arrowbox_next"> <div id="mm-nav-next" class="nav next" onclick="WWL.arrowbox.move_next(\'%(name)s\')"></div></div>',
        "nav-prev" : '<div id="move_prev_%(name)s" class="wwl_arrowbox_prev"> <div id="mm-nav-prev" class="nav prev" onclick="WWL.arrowbox.move_prev(\'%(name)s\')"></div></div>'
};


/*redefine WWW_arrowBoxtemplates*/

media_manager._mm_panel = "mm-panel";
media_manager._tmpl = {
			'arrow-box' : { 'tmpl' : 'arrowbox-render', 'cback' : '_render_arrowbox' },
			'icons' : { 'tmpl' : 'start-view', 'cback' : '_render_icons' },
			'gallery' : '<div id="mm-gallery"></div>' +
				'<div id="mm-gallery-buttons">' +
				'	<div id="mm-button-prev" onclick="media_manager.gallery_prev()"></div>' +
				'	<div id="mm-button-next" onclick="media_manager.gallery_next()"></div>' +
				'</div>',
			'popup' : '<div id="mm-popup-close" onclick="media_manager.gallery_close()"></div>' +
				'<div id="mm-popup-content"></div>'
			};


function MediaManagerItem ( data, templ_preview, templ_full )
{
	var self = this;

	this.data = data;
	this._t_preview = templ_preview;
	this._t_full    = templ_full;
	
	this.preview = function ( mode )
	{
		if ( ! mode ) mode = "icon";

		this.data [ '_mode' ] = mode;
		// var s = String.formatDict ( MediaManagerItem.templates [ this.data [ 'kind' ] + "-preview" ], data );
		return String.formatDict ( this._t_preview, this.data );
	};

	this.toString = function ()
	{
		// return String.formatDict ( MediaManagerItem.templates [ this.data [ 'kind' ] + "-render" ], data );
		return String.formatDict ( this._t_full, this.data );
	};

	this.load = function ( cback )
	{
		if ( this.data [ 'kind' ] != 'image' )
		{
			if ( cback ) cback ();
			return;
		}

		var items = media_manager.instances [ self.data.module + ":" + self.data.id_obj ];

		var cfg_size = items.sizes; // this.data['cfg-sizes'];
		var img = new Image ();

		img.onload = function ()
		{
			//var w = img.width + 40 , h = img.height + 140;
			var w = parseInt ( cfg_size.full.W, 10 ) + 40 , h = parseInt ( cfg_size.full.H, 10 ) + 140;

			$( "mm-show-div" ).style.width = w + "px";
			$( "mm-show-div" ).style.height = h + "px";
			/*
			$( "mm-container" ).style.width = w + "px";
			$( "mm-container" ).style.height = h + "px";
			*/
			liwe.lightbox.set_size ( w, h, -1, -1 );
			if ( cback ) cback ();
		};

		img.src = String.formatDict ( "/site/media_manager/image/full/%(id_media)s.jpg", this.data );

		// if ( cback ) cback ();
	};
}

MediaManagerItem.templates = 
	{
		"image-preview"  : '<img src="/site/media_manager/image/%(_mode)s/%(id_media)s.jpg" alt="%(descr)s" title="%(descr)s" border="0" />',
		"image-render"  : '<img src="/site/media_manager/image/full/%(id_media)s.jpg" alt="%(descr)s" title="%(descr)s" border="0" />',

		"youtube-preview"  : '<img src="/site/media_manager/youtube/%(_mode)s/%(id_media)s.jpg" alt="%(descr)s" title="%(descr)s" border="0" />',
		"youtube-render" : '<object width="618" height="500"><param name="movie" value="http://www.youtube.com/v/%(data)s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/%(data)s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="618" height="500"></embed></object>',

		"start-view" : '<a href="javascript:media_manager.show(\'%(module)s\',\'%(id_obj)s\',%(_pos)d)">%(_img)s</a>',
		"start-gallery" : '<a href="javascript:media_manager.gallery(\'%(module)s\',\'%(id_obj)s\',%(_pos)d)">%(_img)s</a>',
		"flash-preview" : '<object width="200" height="200"><param name="movie" value="/site/media_manager/flash/orig/%(id_media)s.swf"></param><param name="wmode" value="transparent"></param><embed src="/site/media_manager/flash/orig/%(id_media)s.swf" type="application/x-shockwave-flash" wmode="transparent" width="200" height="200"></embed></object>',
		"flash-render" : '<object width="200" height="200"><param name="movie" value="/site/media_manager/flash/orig/%(id_media)s.swf"></param><param name="wmode" value="transparent"></param><embed src="/site/media_manager/flash/orig/%(id_media)s.swf" type="application/x-shockwave-flash" wmode="transparent" width="200" height="200"></embed></object>',

		"wait" : '<div class="liwe_progress"><div class="medium_white"></div></div>',
		//"arrowbox-render" : '<div class="arrow-item"><a href="javascript:media_manager.show(\'%(module)s\',\'%(id_obj)s\',%(_pos)d)">%(_img)s</a></div>',
		"arrowbox-render" : '<div class="arrow-item" style="vertical-align:middle;" onclick ="media_manager.show(\'%(module)s\',\'%(id_obj)s\',%(_pos)d)">%(_img)s</div>',
		"ligth-box-panel" : '<div id="mm-container" align="center"><div id="mm-tbar"><div id="mm-tbar-close" onclick="liwe.lightbox.close()"></div></div><div id="mm-object"></div><div id="mm-panel" class="panel"></div></div>'
	};

media_manager.instances = {};
media_manager.order_mode = {};

media_manager.get_items = function ( module, id_obj, cback, templates, force, order_mode )
{
	var inst = module + ":" + id_obj;
	if ( media_manager.instances [ inst ] && media_manager.order_mode [ inst ] == order_mode && ! force )
	{
		if ( cback ) cback ( media_manager.instances [ inst ] );
		return;
	}

	media_manager.ajax ( { action: "media_manager.ajax.get_items", module: module, id_obj: id_obj, order_mode : order_mode }, 
		function ( v )
		{
			media_manager.order_mode [ inst ] = order_mode
			media_manager._set_items ( v, module, id_obj, templates, cback );
		} );
};

media_manager.get_items_list = function ( module, id_obj, order_mode )
{
	var inst = module + ":" + id_obj;
	//if ( media_manager.instances [ inst ] && media_manager.order_mode [ inst ] == order_mode )
	if ( media_manager.instances [ inst ] ) 
		return media_manager.instances [ inst ];
	return [];
};

media_manager._set_items = function ( v, module, id_obj, templates, cback )
{
	// console.debug ( "SET ITEMS: module: %s - id_obj: %s - items: %o - sizes: %o", module, id_obj, v [ 'media_items' ], v [ 'sizes' ] );

	if ( ! templates ) templates = MediaManagerItem.templates;

	var items = v [ 'media_items' ];
	var sizes = v.get ( "sizes" );
	if ( ! items ) items = [];

	var t, l = items.length;
	var lst = [], data;

	for ( t = 0; t < l; t ++ )
	{
		data = v [ 'media_items' ] [ t ];
		lst.push ( media_manager._create ( data, templates ) );
	}

	lst.sizes = sizes;
	media_manager.instances [ module + ":" + id_obj ] = lst;

	if ( cback ) return cback ( lst );

	return lst;
};

media_manager._create = function ( data, templates )
{
	var preview, full;
	var mmi;

	preview = templates [ data [ 'kind' ] + "-preview" ];
	full    = templates [ data [ 'kind' ] + "-render" ];

	mmi = new MediaManagerItem ( data, preview, full );

	return mmi;
};

media_manager.set_items = function ( items, templates, sizes )
{
	if ( ! items ) return [];

	var it = items;

	// if ( typeof it [ 'media_items' ] != "undefined" ) it = items [ 'media_items' ];
	it = it.get ( "media_items", items );
	// FIXME: controllare qui se ancora valido items ora dovrebbe essere { 'media_items' : [...] , 'cfg_sizes' : {...} }
	if ( ! it || ! it.length ) return [];

	return media_manager._set_items ( { "media_items" : it, "sizes" : sizes }, it [ 0 ] [ 'module' ], it [ 0 ] [ 'id_obj' ], templates );
};

media_manager.panel = function ( items, mode, items_per_row, cback, tmpl )
{
	if ( ! mode ) mode = "icon";
	if ( ! items_per_row ) items_per_row = 8;
	if ( ! cback ) cback = media_manager._render_icons;
	if ( ! tmpl ) tmpl = ( mode == 'gallery' ? 'start-gallery' : 'start-view' );

	return cback ( items, mode, MediaManagerItem.templates [ tmpl ],  items_per_row );
};
	
media_manager.show = function ( module, id_obj, pos, width, force, mode, items_per_row, render , cback )
{
	// console.debug ( "SHOW: module: %s - id_obj: %s", module, id_obj );

	var items = media_manager.instances [ module + ":" + id_obj ];

	if ( ! items || ! items.length ) 
	{
		$( "mm-object", "" );
		$( "mm-panel", "" );
		return;
	}

	var mi = items [ pos ];
	var div, res;
	var lb_created = liwe.lightbox.created ();

	if ( ! mode ) mode = 'icon';
	if ( ! items_per_row )  items_per_row = 4;
	var dict =  media_manager._tmpl.get ( render, media_manager._tmpl [ 'arrow-box' ] );

	if ( ! cback ) cback = media_manager [ dict [ 'cback' ] ];
	var tmpl = dict.tmpl;

	
	if ( ! width ) width = 1000;

	if ( ! lb_created || force )
	{
		liwe.lightbox.events [ 'click' ] = function () { liwe.lightbox.close (); };

		if ( ! lb_created ) 
		{
		
			div = liwe.lightbox.create ( "mm-show-div", width ); //, width, 950 );
			
			div.innerHTML = MediaManagerItem.templates [ 'ligth-box-panel' ];

			//div.innerHTML = '<div id="mm-container" align="center"><div id="mm-tbar"><div id="mm-tbar-close" onclick="liwe.lightbox.close()"></div></div><div id="mm-object"></div><div id="mm-panel" class="panel"></div></div>';
			//div.innerHTML = '<div id="mm-container" align="center"><div id="mm-object"></div><div id="mm-panel" class="panel"></div></div>';
		}

		res = media_manager.panel ( items, mode, items_per_row, cback, tmpl )
		//media_manager._render_arrowbox ( 'mm-panel', items, 'icon', MediaManagerItem.templates [ 'arrowbox-render' ], 4 );
		//$( "mm-panel", media_manager._render_icons ( items, "icon", MediaManagerItem.templates [ 'start-view' ], 8 ) );
		if ( res ) $( "mm-panel", res );
		if ( ! lb_created ) liwe.lightbox.show ();
	}

	mi.load ( function ()
	{
		$( "mm-object", mi.toString () );
	} );
};



media_manager._render_arrowbox =  function ( items, mode, template, viewed_items )
{
	var full_width = parseInt( items.sizes [ 'full' ].W, 10 );
	var size = items.sizes [ mode ];
	var items_width = parseInt ( items.length * ( size.W + 20 ), 10 ); 
	if ( full_width > items_width )
	{
		var tmpl = ( mode == 'gallery' ? MediaManagerItem.templates [ 'start-gallery' ] : MediaManagerItem.templates [ 'start-view' ] );
		return media_manager._render_icons ( items, 'icon' , tmpl , items.length );
	}

	var dest_div = media_manager._mm_panel;
	var arr_box = new WWL.arrowbox ( 'arrow_box' );
	// var inst = media_manager.instances;
	// var inst_name = items [ 0 ][ 'data' ][ 'module' ] + ':' + items [ 0 ][ 'data' ][ 'id_obj' ] ;
	
	// arr_box.set_size ( (parseInt( size.W , 10 ) + 2 ) * viewed_items, parseInt( size.H, 10 ) +2 );
	//arr_box.set_size ( full_width - 78, parseInt( size.H, 10 ) +2 );
	arr_box.set_size ( full_width , parseInt( size.H, 10 ) +2 );
	arr_box.set_item_size ( parseInt ( size.W, 10 ) + 20 ,parseInt ( size.H, 10 ) + 4  );
	arr_box.set_arrow_w ( 36 );
	items.iterate ( function ( el, k )
	{
		if ( k == 'sizes' ) return;

		dct = { "id_obj" : el.data [ 'id_obj' ], "module" : el.data [ 'module' ], _pos: k, _img: el.preview ( mode ) };
		arr_box.add_item ( String.formatDict ( template, dct ) );
	});
	arr_box.render ( dest_div );
	var arr_margin = Math.floor ( ( size.H - 36 ) / 2 );
	$( 'mm-nav-next' ).style.marginTop= arr_margin + "px";
	$( 'mm-nav-prev' ).style.marginTop= arr_margin + "px";

	return '';
};


media_manager._render_icons = function ( items, mode, template, items_per_row )
{
	var t, l = items.length;
	var res = new String.buffer ();
	var mi, dct, _mode = mode;
	var count = 0;

	if ( mode == 'gallery' ) _mode = 'icon';

	res.add ( '<table border="0" class="media_manager_icons">' );
	
	for ( t = 0; t < l; t ++ )
	{
		if ( ! count ) res.add ( "<tr>" );
		count ++;

		mi = items [ t ];
		
		dct = { "id_obj" : mi.data [ 'id_obj' ], "module" : mi.data [ 'module' ], _pos: t, _img: mi.preview ( _mode ), "id_media" : mi.data [ 'id_media' ] };

		res.add ( '<td>' );
		res.add ( String.formatDict ( template, dct ) );
		res.add ( '</td>' );

		if ( count == items_per_row ) 
		{
			res.add ( '</tr>' );
			count = 0;
		}
	}
	if ( count ) res.add ( '</td></tr>' );
	res.add ( '</table>' );

	return res.toString ();
};

media_manager.gallery = function ( module, id_obj, pos )
{
	pos = pos || 0;
	media_manager._init_gallery ();
	media_manager.get_items ( module, id_obj, function ( items )
	{
		media_manager._gallery_images = items;
		$( 'mm-popup-content', media_manager._tmpl [ 'gallery' ] );
		media_manager.gallery_page ( pos );
		liwe.dom.show ( 'mm-popup' );

		media_manager.dispatchEvent ( 'gallery', null );
	} );
};

media_manager.gallery_page = function ( n )
{
	if ( ! n ) n = 0;
	if ( n < 0 ) n = 0;
	if ( n > media_manager._gallery_images.length - 1 ) n = media_manager._gallery_images.length - 1;

	if ( n == 0 )
		liwe.dom.hide ( 'mm-button-prev' );
	else
		liwe.dom.show ( 'mm-button-prev' );

	if ( n == media_manager._gallery_images.length - 1 )
		liwe.dom.hide ( 'mm-button-next' );
	else
		liwe.dom.show ( 'mm-button-next' );

	media_manager._gallery_img = n;

	var img = media_manager._gallery_images [ n ];
	var g = $( 'mm-gallery' );
	g.style.backgroundImage = String.formatDict ( "url(/site/media_manager/image/full/%(id_media)s.jpg)", img [ 'data' ] );
};

media_manager.gallery_prev = function ()
{
        media_manager.gallery_page ( media_manager._gallery_img - 1 );
};

media_manager.gallery_next = function ()
{
        media_manager.gallery_page ( media_manager._gallery_img + 1 );
};

media_manager.gallery_close = function ()
{
	liwe.dom.hide ( 'mm-popup' );
	media_manager.dispatchEvent ( 'close', null );
};

media_manager._init_gallery = function ()
{
	if ( $( 'mm-popup' ) ) return;
	var c = document.createElement ( 'div' );
	c.id = 'mm-popup';
	c.style.display = 'none';
	c.innerHTML = media_manager._tmpl [ 'popup' ];
	document.body.appendChild ( c );
};
